//
const fs = require('fs');
const path = require('path');
const Config = global.UEditorConfig;

// static
const sourceUpBasePath = path.resolve('.', Config.upBaseURL);
const sourceUpPath = path.resolve(sourceUpBasePath, Config.upSaveURL);

//
function getList(fullURL, pram_path) {
  let accessURI = pram_path.substr(sourceUpBasePath.length + 1).replace(/\\/g, '\/');
  let file_list;
  try{
    file_list = fs.readdirSync(pram_path);
  } catch(e) {
    file_list = []
  }
  file_list = file_list.map(item => {
    return {
      url: fullURL + accessURI + item,
      mtime: ''
    };
  });
  return file_list;
}

// 请求处理
module.exports = function(req, res, next) {
  let actionType = req.query.action;
  let allowFiles, listSize, $path;
  // 图片或者文件
  if(actionType === 'listimage'){
    allowFiles = Config['imageManagerAllowFiles'];
    listSize = Config['imageManagerListSize'];
    $path = path.join(sourceUpPath, Config['imageManagerListPath']);
  } else {
    // listfile
    allowFiles = Config['fileManagerAllowFiles'];
    listSize = Config['fileManagerListSize'];
    $path = path.join(sourceUpPath, Config['fileManagerListPath']);
  }

  /* 获取参数 */
  let $size = Number(req.query.size) || listSize;
  let $start = Number(req.query.start) || 0;
  let $end = $start + $size;

  /* 获取列表 */
  let list = getList(req.fullURL, $path) || [];

  //
  res.json({
    state: 'SUCCESS',
    list: list,
    start: $start,
    total: list.length
  });
}
